from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_jwt_extended import JWTManager
from flask_cors import CORS
from config import config

db = SQLAlchemy()
migrate = Migrate()
jwt = JWTManager()


def create_app(config_name='default'):
    """应用工厂函数"""
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    
    # 初始化扩展
    db.init_app(app)
    migrate.init_app(app, db)
    jwt.init_app(app)
    
    # 配置CORS支持跨域
    CORS(app, 
         origins=['*'],  # 允许所有域名
         methods=['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],  # 允许的HTTP方法
         allow_headers=['Content-Type', 'Authorization'],  # 允许的请求头
         supports_credentials=True  # 支持携带凭证
    )
    
    # 注册蓝图
    from app.api.admin.v1 import admin_bp
    app.register_blueprint(admin_bp, url_prefix='/admin/v1')
    
    # 注册文件API蓝图
    from app.api.files import files_bp
    app.register_blueprint(files_bp, url_prefix='/api/files')
    
    # 注册用户认证蓝图
    try:
        from app.api.auth.v1 import user_auth_bp
        app.register_blueprint(user_auth_bp, url_prefix='/api/auth/v1')
        print("✅ 用户认证蓝图注册成功")
    except ImportError as e:
        print(f"❌ 用户认证蓝图注册失败 - ImportError: {e}")
        import traceback
        traceback.print_exc()
    except Exception as e:
        print(f"❌ 用户认证蓝图注册失败 - 其他错误: {e}")
        import traceback
        traceback.print_exc()
    
    # 注册用户基础信息管理蓝图
    try:
        from app.api.users.v1 import user_v1_bp
        app.register_blueprint(user_v1_bp, url_prefix='/api/users/v1')
        print("✅ 用户基础信息管理蓝图注册成功")
    except ImportError as e:
        print(f"❌ 用户基础信息管理蓝图注册失败 - ImportError: {e}")
        import traceback
        traceback.print_exc()
    except Exception as e:
        print(f"❌ 用户基础信息管理蓝图注册失败 - 其他错误: {e}")
        import traceback
        traceback.print_exc()
    
    # 注册字典管理蓝图
    try:
        from app.api.v1.dict import dict_bp
        app.register_blueprint(dict_bp)
        print("✅ 字典管理蓝图注册成功")
    except ImportError as e:
        print(f"❌ 字典管理蓝图注册失败 - ImportError: {e}")
        import traceback
        traceback.print_exc()
    except Exception as e:
        print(f"❌ 字典管理蓝图注册失败 - 其他错误: {e}")
        import traceback
        traceback.print_exc()
    
    # 注册Swagger文档蓝图
    try:
        from app.swagger_docs import doc_bp
        app.register_blueprint(doc_bp, url_prefix='/api')
        print("✅ Swagger文档蓝图注册成功")
    except ImportError as e:
        print(f"❌ Swagger文档蓝图注册失败 - ImportError: {e}")
        # 如果Flask-RESTX未安装，跳过Swagger文档
        pass
    except Exception as e:
        print(f"❌ Swagger文档蓝图注册失败 - 其他错误: {e}")
        import traceback
        traceback.print_exc()
    
    # 注册测试认证接口
    try:
        from app.api.test_auth import register_test_auth
        register_test_auth(app)
        print("✅ 测试认证接口注册成功")
    except ImportError as e:
        print(f"❌ 测试认证接口注册失败 - ImportError: {e}")
    except Exception as e:
        print(f"❌ 测试认证接口注册失败 - 其他错误: {e}")
        import traceback
        traceback.print_exc()
    
    # 注册匹配算法API
    try:
        from app.api.v1.matching import matching_bp
        app.register_blueprint(matching_bp, url_prefix='/api/v1')
        print("✅ 匹配算法API注册成功")
    except ImportError as e:
        print(f"❌ 匹配算法API注册失败 - ImportError: {e}")
    except Exception as e:
        print(f"❌ 匹配算法API注册失败 - 其他错误: {e}")
        import traceback
        traceback.print_exc()
        
    # 注册V1版本API蓝图（包含轮播图等接口）
    try:
        from app.api.v1 import register_v1_blueprints
        register_v1_blueprints(app)
        print("✅ V1版本API蓝图注册成功")
    except ImportError as e:
        print(f"❌ V1版本API蓝图注册失败 - ImportError: {e}")
        import traceback
        traceback.print_exc()
    except Exception as e:
        print(f"❌ V1版本API蓝图注册失败 - 其他错误: {e}")
        import traceback
        traceback.print_exc()

    return app 